
package com.kugou.game.sdk.statistics;

import com.kugou.framework.base.LogUtil;
import com.kugou.framework.http.KGHttpClient;
import com.kugou.framework.http.RequestPackage;
import com.kugou.framework.http.ResponsePackage;
import com.kugou.framework.utils.UrlEncodeUtil;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.NetWorkUtil;
import com.kugou.game.sdk.utils.UrlWrapper;

import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.text.TextUtils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Set;

/**
 * 描述:抽象统计任务
 *
 * @author jerryliu
 * @since 2015年11月23日 上午11:56:44
 */
@SuppressWarnings("rawtypes")
public abstract class AbsStatisticsTask implements RequestPackage, ResponsePackage {

    public static final String TAG = "Statistics";

    protected Context mContext;

    private HashMap<String, String> mParams = new HashMap<String, String>();

    public AbsStatisticsTask(Context context) {
        this.mContext = context;
    }

    public String getCommonParams() {
        Context context = mContext == null ? mContext : SDKControler.getContext();
        StringBuilder commonParams = new StringBuilder();
        /*--公共参数--*/
        // 固定参数
        try {
            // merchantid
            commonParams.append("&merchantid=" + SDKControler.getMerchantId());
            // appid
            commonParams.append("&appid=" + SDKControler.getAppId());
            // gameid
            commonParams.append("&gameid=" + SDKControler.getGameId());
            // serverid
            commonParams.append("&serverid=" + SDKControler.getServerId());
            // imei
            commonParams.append("&imei="
                    + UrlEncodeUtil.encode(AppUtil.getMachineSN(context), "UTF-8"));
            // 渠道号
            commonParams.append("&channelid=" + SDKControler.getChannelId());
            // 平台，1为android，2为ios官方版，3为ios越狱版
            commonParams.append("&platform=" + 1);
            // 手机型号
            commonParams.append("&model=" + UrlEncodeUtil.encode(AppUtil.getPhoneModel(), "UTF-8"));
            // 网络类型，1=wifi，2=2g，3=3g，4=4g,5=未知
            commonParams.append("&nettype=" + AppUtil.getNetworkType(context));
            // uuid
            commonParams.append("&uuid="
                    + UrlEncodeUtil.encode(AppUtil.getKugouUUID(context), "UTF-8"));
            // mid
            commonParams.append("&mid="
                    + UrlEncodeUtil.encode(AppUtil.getKugouMID(context), "UTF-8"));
            // SDK版本名称
            commonParams.append("&clientversionname="
                    + UrlEncodeUtil.encode(SDKControler.getSDKVersionName(), "UTF-8"));
            // SDK版本号
            commonParams.append("&clientversioncode=" + SDKControler.getSDKVersionCode());
            // 游戏版本名称
            commonParams.append("&appversion="
                    + UrlEncodeUtil.encode(AppUtil.getVersionName(context), "UTF-8"));
            // 游戏版本号
            commonParams.append("&appversioncode=" + AppUtil.getVersionCode(context));
            // 客户端类型(0:游戏sdk，1:hi游sdk，2:h5sdk)
            commonParams.append("&clienttype=" + 0);
            // sdk类型，0:网游、1:单机
            commonParams.append("&sdktype=" + SDKControler.getGameType());
            // 运营商id1：移动2：联通3：电信4：其它
            commonParams.append("&spid=" + AppUtil.getMNCNum(mContext));
            // 分辨率
            commonParams.append("&resolution=" + AppUtil.getScreenSizeStr(mContext));
            // 系统版本
            commonParams.append("&opsystemversion="
                    + UrlEncodeUtil.encode(AppUtil.getSysVersionName(), "UTF-8"));
            User user = UserManager.getInstance().getCurrentUserInternal();
            // 用户名
            commonParams.append("&username="
                    + UrlEncodeUtil.encode(user == null ? "" : user.getAccountName(), "UTF-8"));
            // 酷狗id
            commonParams.append("&kgid="
                    + UrlEncodeUtil.encode(user == null ? "" : user.getKugouid(), "UTF-8"));
            // openid
            commonParams.append("&openid="
                    + UrlEncodeUtil.encode(user == null ? "" : user.getOpenId(), "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return commonParams.toString();
    }

    @Override
    public String getGetRequestParams() {
        StringBuilder getParams = new StringBuilder(getCommonParams());
        if (mParams != null && mParams.size() > 0) {
            getParams.append("&");
            final Set<String> keys = mParams.keySet();
            for (String key : keys) {
                getParams.append(key).append("=").append(mParams.get(key)).append("&");
            }
            getParams.deleteCharAt(getParams.length() - 1);
        }
        String str = getParams.toString();
        LogUtil.d(TAG, getClass().getSimpleName() + "-->" + UrlWrapper.STATICS_DEFAULT_URL + str);
        return str;
    }

    @Override
    public HttpEntity getPostRequestEntity() {
        if (mParams != null && mParams.size() > 0) {
            Set<String> keySet = mParams.keySet();
            ArrayList<BasicNameValuePair> keyValues = new ArrayList<BasicNameValuePair>();
            for (String key : keySet) {
                keyValues.add(new BasicNameValuePair(key, mParams.get(key)));
            }
            try {
                LogUtil.d(TAG, getClass().getSimpleName() + "-->"
                        + UrlWrapper.STATICS_ONLINE_POST_URL + "--getPostRequestEntity");
                return new UrlEncodedFormEntity(keyValues);
            } catch (UnsupportedEncodingException e) {
            }
        }
        return null;
    }

    @Override
    public void getResponseData(Object t) {
    }

    /**
     * 执行统计
     */
    @SuppressWarnings("unchecked")
    public void execute() {
        if (!NetWorkUtil.isNetworkAvailable(mContext)) {
            onFaile("network error");
            return;
        }
        if (!canSend()) {
            onFaile("can't send");
            return;
        }
        initParams(mParams);
        try {
            if (TextUtils.isEmpty(getUrl())) {
                onFaile("url illegal");
                return;
            }
            KGHttpClient.request(this, this);
        } catch (Exception e) {
            onFaile("server error");
        }
    }

    @Override
    public void setContext(byte[] data) {
        if (data != null) {
            doWithResult(data);
        } else {
            onFaile("server error");
        }
    }

    @Override
    public Hashtable<String, String> getRequestHeaders() {
        return null;
    }

    @Override
    public Hashtable<String, Object> getSettings() {
        return null;
    }

    /**
     * 处理结果
     * 
     * @param data
     */
    public void doWithResult(byte[] data) {
        String result = new String(data);
        LogUtil.d(TAG, getClass().getSimpleName() + " result:" + result);
    }

    /**
     * 失败
     * 
     * @param msg
     */
    public void onFaile(String msg) {
        LogUtil.e(TAG, msg);
    }

    /**
     * 是否满足发送条件，可以重写这个方法来控制是否发送这个统计数据
     */
    public boolean canSend() {
        return true;
    }

    /**
     * 初始化参数
     * 
     * @param mParams
     */
    public abstract void initParams(HashMap<String, String> params);

    @Override
    public String getUrl() {
        return UrlWrapper.STATICS_DEFAULT_URL;
    }

    @Override
    public int getRequestType() {
        return RequestPackage.TYPE_GET;
    }

}
